"use strict";

const mvc = require('cosjs.mvc');
const path = require('path');
const cosjs = require('cosjs');
const setting = require("./game");
const { Logger } = require('log4js');

const dbsType = { "cache": "redis", "redis": "redis", "mongodb": "mongodb" };
//============================启动进程=================================//
//系统配置，二合一
console.log("process argv --------", process.argv)
let root = path.dirname(process.argv[1]);
console.log("root--------", root)
let file = path.resolve(root, process.argv[2] || 'config');
console.log("file--------", file)
let config = require(file);

let options = Object.assign({}, setting);
// console.log("options:--------------",options)
//合并应用配置
for (let k in config) {
    if (typeof config[k] === 'object' && !Array.isArray(config[k])) {
        options[k] = Object.assign(options[k] || {}, config[k] || {});
    }
    else {
        options[k] = config[k];
    }
}

// console.log("options:--------------2",options)

process.env.NODE_ENV = options.debug ? 'development' : 'production';
mvc.config.set(options);

//初始化命名空间
mvc.model.namespace("redis", "mongo");
mvc.handle.namespace("local", "remote");
//初始化updater

//启动HTTP内部服务
if (options['spirit']) {
    options["local"]['fnum'] = 1;
}
// console.log("options local :%v",options["local"])
cosjs.http(options["local"]);
//启动HTTP远程服务
// console.log("options remote :%v",options["remote"])
cosjs.http(options["remote"]);
//工作进程
cosjs.fork('timer', setting["root"] + '/process/timer');
//服务器性能监控
// if(options['spirit']){
//     cosjs.fork('spirit',setting["root"]+'/process/spirit');
// }

process.on('unhandledRejection', (err) => {
    console.error('Unhandled promise rejection:', err);
});

console.debug = mvc.debug;
//启动入口
exports.start = function () {
    return cosjs.start(server_start);
}
//开服入口，node,file,config,sid
exports.install = function () {
    let sid = process.argv[3];
    return server_start('install').then(() => {
        return require('./install')(sid);
    }).then(() => {
        console.log("app install success");
        process.exit();
    }).catch(err => {
        console.log('app install fail:', err)
        process.exit();
    })
}

exports.debug = function () {
    return server_start('debug');
}

//启动进程时
function server_start(name) {
    // console.log("name------:%s",name)
    return Promise.resolve().then(() => {
        console.log("setting root------:%s", setting["root"])
        return mvc.addPath(setting["root"]);  //初始化框架路径
    }).then(() => {
        return mvc.addPath(options["root"]);   //初始化项目路径
    }).then(() => {
        return pool_connect(name, 0);
    }).then(() => {
        let multi = mvc.library("multi", options.sid, pool_connect.bind(this, name));
        return multi.start();
    }).then(() => {
        //初始化updater
        let iTypes = mvc.config("iTypes");
        // console.log("iTypes:%v",iTypes)
        require('cosjs.updater').initialize(iTypes, 2);
    })
}


//连接数据库池

function pool_connect(name, sid) {
    console.log("pool name and sid :  %s    %s ", name, sid)
    let nodbworker = ['timer', 'spirit', 'socket'];

    if (nodbworker.indexOf(name) >= 0) {
        return Promise.resolve(1);
    }

    let opt, dbs = options.dbs[sid] || 0;
    if (typeof dbs === 'number') {
        opt = { "cache": dbs, "redis": dbs, "mongodb": dbs }
        console.log("dbs data 1:%v", opt)
    }
    else {
        opt = dbs;
        console.log("dbs data 2:%v", opt)
    }

    let worker = db_connect.bind(null, opt, sid);
    let multi = mvc.library("multi", dbsType, worker);
    return multi.start();
}


function db_connect(opt, sid, k) {
    let v = opt[k];
    let pk = [k, sid].join("");
    let ty = typeof v;
    if (ty === 'number') {
        let tk = [k, v].join("")
        return cosjs.pool.link(pk, tk);
    }
    else if (ty === 'string' && v.indexOf(k) === 0) {
        return cosjs.pool.link(pk, v);
    }
    else {
        let dbkey = dbsType[k];
        return cosjs.pool[dbkey](pk, v);
    }
}